//
//  AdvertListViewModel.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/6/13.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class AdvertListViewModel: BaseViewModel {
    var states:Int = 1 //上架下架状态
    @objc dynamic  var refreshBool = false //监听的状态
    var refreshAll:Bool = false // 刷新全部
    var page = 1 //页码
    var size  = 10 //页面数量
    var underPage = 1//下架页码
    var underSize = 10//下架数量
    var selectIndex:Int = 0 //0 进行中 1 下架
    var changeModel:AdvertInforModel? //修改状态的数据源
    lazy var dateArr:Array<AdvertInforModel> = {
        let array:Array<AdvertInforModel> = []
        return array
    }()
    lazy var undercarriageArr:Array<AdvertInforModel> = {
        let array:Array<AdvertInforModel> = []
        return array
    }()
    lazy var request: AdvertListRequest = {
        let api = AdvertListRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var stateRequest: AdvertStateRequest = {
        let api = AdvertStateRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    override init(controller: BaseViewController) {
        super.init(controller: controller)
    }
    
    //初始化获取全部数据
    func archiveAll() {
        CYMBShow.openIndicator(message: nil, view: self.controller?.view)
        self.refreshAll = true
        page = 1
        underPage = 1
        let group  = DispatchGroup()
        let quene = DispatchQueue(label: "queuename")
        quene.async(group: group, qos: .default, flags: []) {
            let semaphore =  DispatchSemaphore(value: 0)
            self.archiveInfromation(statesBool: 1, semaphore: semaphore)
            semaphore.wait()
        }
        quene.async(group: group, qos: .default, flags: []) {
            let semaphore =  DispatchSemaphore(value: 0)
            self.archiveInfromation(statesBool: 0, semaphore: semaphore)
            semaphore.wait()
        }
        group.notify(queue: DispatchQueue.main) {
            self.refreshAll = false
            CYMBShow.colseIndicator(view: self.controller?.view)
        }
    }
    
    
    /// 获取上架 下架数据源
    ///
    /// - Parameters:
    ///   - statesBool: 状态 1 进行中 0 下架
    ///   - semaphore: 信号源
    func archiveInfromation(statesBool:Int,semaphore:DispatchSemaphore?)  {
        self.states = statesBool
        self.request(request: request, success: {[weak self] (result) in
            semaphore?.signal()
            let dic:[String:Any]? = result != nil ? result : nil
            if dic == nil {
                return
            }
            if dic?["data"] as? [String : Any] == nil  {
                return
            }
            
            if statesBool == 1 {
                if self?.page == 1 {
                    self?.dateArr.removeAll()
                }
            let model = AdvertListModel(JSON: (dic?["data"] as? [String : Any])!)
            if model?.list != nil {
                self?.dateArr  = (self?.dateArr)! + (model?.list)!
            }
                
            }else {
                if self?.underPage == 1 {
                    self?.undercarriageArr.removeAll()
                }

                let model = AdvertListModel(JSON: (dic?["data"] as? [String : Any])!)
                if model?.list != nil {
                    self?.undercarriageArr  = (self?.undercarriageArr)! + (model?.list)!
                }
                
            }
            self?.refreshBool = true
        }) {[weak self] (fail) in
            semaphore?.signal()
            self?.refreshBool = false
        }
    }
    
    
    /// 修改状态
    ///
    /// - Parameter index: index
    func changeAdvertStates(index:Int)  {
        if selectIndex == 0 {
            changeModel = dateArr[index]
            stateRequest.states = 0
        }else {
            changeModel = undercarriageArr[index]
            stateRequest.states = 1
        }
        stateRequest.inforId = String(format: "%d", changeModel?.id ?? 0)
        self.request(request: stateRequest, success: {[weak self] (result) in
            CYMBShow.showMessage(kText("修改广告状态成功"))
            NotificationCenter.default.post(name: NSNotification.Name.Exchange.adListNeedRefresh, object: nil)
            self?.archiveAll()
        }) { (response) in
            if response.errorMsg.count != 0 {
            CYMBShow.showMessage(response.errorMsg)
            }
        }
    }
    
    

}
extension AdvertListViewModel: RequestCallBack,RequestDataReformer,RequestParamSource {
    func reform(_ request: BaseRequest, _ data: [String : Any]?) {
        if successBlock != nil {
            successBlock!(data)
        }
    }
    
    func requestDidSucess(_ request: BaseRequest) {
        
    }
    
    func requestDidFail(_ request: BaseRequest) {
        if failBlock != nil {
            failBlock!(request)
        }
    }
    
    func requestParams(_ request: BaseRequest) -> [String : Any]? {
        var pramas: [String:Any] = [:]
        if let _ = request as? AdvertListRequest {
        pramas.updateValue(states, forKey: "status")
        pramas.updateValue(page, forKey: "page")
        pramas.updateValue(size, forKey: "size")
        }
        return pramas
    }
    
    
    
}
